<!--
 * @Author: daidai
 * @Date: 2022-03-01 11:17:39
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-09-29 15:50:18
 * @FilePath: \web-pc\src\pages\big-screen\view\indexs\center-map.vue
-->
<template>
  <div class="centermap">
    <div class="maptitle">
      <div class="zuo"></div>
      <span class="titletext">{{ maptitle }}</span>
      <div class="you"></div>
    </div>
    <div class="mapwrap">
      <dv-border-box-13>
        <div class="quanguo" @click="back()" v-if="adcodes.length != 0">
          返回
        </div>
        <div class="quanguo" @click="map_flag = true" v-show="!map_flag">
          返回
        </div>
        <div class="current" v-if="current != ''">
          {{ current }}
        </div>
        <Echart id="CenterMap" :options="options" ref="CenterMap" v-show="map_flag"/>
        <!-- <iframe src="/map-bin.html" frameborder="0" style="width:100%;height:100%;" v-show="!map_flag"></iframe> -->
      </dv-border-box-13>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import * as API from "@/api/api";
export default {
  data() {
    return {
      maptitle: "事故分布图",
      options: {},
      code: "chinaNanhai", //china 代表中国 其他地市是行政编码
      echartBindClick: false,
      isSouthChinaSea: true, //是否要展示南海群岛  修改此值请刷新页面
      adcodes: [],
      current: '',
      // iframe开关
      map_flag:true,
      bigCity: 0,
    };
  },
  created() {},

  mounted() {
    this.getData("chinaNanhai");
  },
  methods: {
    back() {
      this.adcodes.pop();
      if (this.adcodes.length == 0) {
        this.getData('chinaNanhai');
        this.current = '';
        this.$store.state.adcode = 0;
        return;
      }
      this.getData(this.adcodes[this.adcodes.length - 1].adcode);
      this.current = this.adcodes[this.adcodes.length - 1].name; 
      // 更新全局adcode值
      this.$store.state.adcode = this.adcodes[this.adcodes.length - 1].adcode
    },
    getData(code) {
      this.getGeojson(code);
      this.mapclick();
    },
    /**
     * @description: 获取geojson
     * @param {*} name china 表示中国 其他省份行政区编码
     * @param {*} mydata 接口返回列表数据
     * @return {*}
     */
    async getGeojson(name) {
      this.code = name;
      // 获取子级区域的地图 pid=0获取省级地图
      let pid = 0;
      //如果要展示南海群岛并且展示的是中国的话
      let mapjson;
      if (name == 'china' || name == 'chinaNanhai') {
        // 全国地图从项目中获取
        mapjson = await API.GETNOBASE(`./map-geojson/${name}.json`).then((res) => {
          return res;
        });
      } else {
        const theMap = await API.GET('/maps/getMap',{adcode: name}).then((res) => {
          if (res.code === '0') {
            return res.data;
          }
          return null;
        })
        if (theMap == null || theMap.geo == undefined || theMap.geo == null) {
          // 可能是后台配置的数据有误
          this.message('请先配置地图数据');
          return;
        }
        mapjson = theMap.geo;
        // 获取其子级的地图
        pid = theMap.id;
      }
      // 请求下级地图数据
      const data = await API.GET('/maps',{ pid: pid }).then(res => {
        if (res.code === '0') {
          return res.data;
        }
        return [];
      });
      // 获取区域中心点
      let centries = [];
      if (mapjson.features == undefined) {
        // 将数据库字符串转json
        mapjson = JSON.parse(mapjson);
      }
      // 不是区地图就找中心点
      mapjson.features.forEach(el => {
        if (el.properties.name == '香港特别行政区' || el.properties.name == '澳门特别行政区' || el.properties.name == '台湾省') {
          return;
        }
        if (el.properties != undefined) {
          if (el.properties.centroid) {
            centries.push({ name: el.properties.name, value: el.properties.centroid });
            return;
          }
          centries.push({ name: el.properties.name, value: el.properties.center });
        }
      });
      // // 请求事故数据
      // let uri = '/traffic';
      // let provinceName,cityName,districtName;
      // if (this.current == '北京市' || this.current == '天津市' || this.current == '上海市' || this.current == '重庆市') {
      //   // 直辖市，直接请求区县数据
      //   // 更新标识
      //   this.bigCity = 1;
      // }
      // if (this.bigCity == 1) {
      //   // 直辖市，直接请求区县
      //   switch (this.adcodes.length) {
      //     case 1:
      //       uri += '/district';
      //       provinceName = this.adcodes[0].name;
      //       cityName = this.adcodes[0].name;
      //       break; //获取省内各市
      //     case 2:
      //       uri += '/list';
      //       districtName = this.adcodes[this.adcodes.length - 1].name;
      //       break; // 获取市内各区县
      //   }
      // } else {
      //   switch (this.adcodes.length) {
      //     case 0:
      //       uri += '/province'; break; //获取全国省市
      //     case 1:
      //       uri += '/city';
      //       provinceName = this.adcodes[this.adcodes.length - 1].name
      //       break; //获取省内各市
      //     case 2:
      //       uri += '/district';
      //       provinceName = this.adcodes[this.adcodes.length - 2].name
      //       cityName = this.adcodes[this.adcodes.length - 1].name
      //       break; // 获取市内各区县
      //     case 3:
      //       uri += '/list';
      //       districtName = this.adcodes[this.adcodes.length - 1].name;
      //       break; // 获取区县内坐标
      //   }
      // }
      // 获取事故数据
      const targetData = await API.GET('/traffic/count', { 
        adcode: (name == 'china' || name == 'chinaNanhai') ? 0 : name
      }).then(res => {
        if (res.code === '0') {
          return res.data;
        }
        return [];
      });
      targetData.forEach(v => {
        centries = centries.map(centerPoint => {
          if (centerPoint.name == v.name) {
            // 将后台返回的value值push到坐标数组里，用于气泡展示
            centerPoint.value.push(v.value);
          }
          return centerPoint;
        });
      });
      echarts.registerMap(name, mapjson);
      // 注册数据
      this.init(name, data, centries);
    },
    init(name, data, data2) {
      let top = 45;
      let zoom = 1.05;
      let option = {
        backgroundColor: "rgba(0,0,0,0)",
        tooltip: {
          show: false,
        },
        legend: {
          show: false,
        },
        // visualMap: {
        //   left: 20,
        //   bottom: 20,
        //   pieces: [
        //     { gte: 1000, label: "1000个以上" }, // 不指定 max，表示 max 为无限大（Infinity）。
        //     { gte: 600, lte: 999, label: "600-999个" },
        //     { gte: 200, lte: 599, label: "200-599个" },
        //     { gte: 50, lte: 199, label: "49-199个" },
        //     { gte: 10, lte: 49, label: "10-49个" },
        //     { lte: 9, label: "1-9个" }, // 不指定 min，表示 min 为无限大（-Infinity）。
        //   ],
        //   inRange: {
        //     // 渐变颜色，从小到大
        //     color: [
        //       "#c3d7df",
        //       "#5cb3cc",
        //       "#8abcd1",
        //       "#66a9c9",
        //       "#2f90b9",
        //       "#1781b5",
        //     ],
        //   },
        //   textStyle: {
        //     color: "#fff",
        //   },
        // },
        geo: {
          map: name,
          roam: false,
          selectedMode: false, //是否允许选中多个区域
          zoom: zoom,
          top: top,
          aspectScale: 0.78,
          show: false,
        },
        series: [
          {
            name: "MAP",
            type: "map",
            map: name,
            // aspectScale: 0.78,
            data: data,
            // data: [1,100],
            selectedMode: false, //是否允许选中多个区域
            zoom: zoom,
            geoIndex: 1,
            top: top,
            tooltip: {
              show: true,
              formatter: function (params) {
                return params.name;
              },
              backgroundColor: "rgba(0,0,0,.6)",
              borderColor: "rgba(147, 235, 248, .8)",
              textStyle: {
                color: "#FFF",
              },
            },
            label: {
              show: false,
              color: "#000",
              // position: [-10, 0],
              formatter: function (val) {
                // console.log(val)
                // if (val.data !== undefined) {
                //   return val.name.slice(0, 2);
                // } else {
                //   return "";
                // }
              },
              rich: {},
            },
            emphasis: {
              label: {
                show: false,
              },
              itemStyle: {
                areaColor: "#389BB7",
                borderWidth: 1,
              },
            },
            itemStyle: {
              borderColor: "rgba(147, 235, 248, .8)",
              borderWidth: 1,
              areaColor: {
                type: "radial",
                x: 0.5,
                y: 0.5,
                r: 0.8,
                colorStops: [
                  {
                    offset: 0,
                    color: "rgba(147, 235, 248, 0)", // 0% 处的颜色
                  },
                  {
                    offset: 1,
                    color: "rgba(147, 235, 248, .2)", // 100% 处的颜色
                  },
                ],
                globalCoord: false, // 缺为 false
              },
              shadowColor: "rgba(128, 217, 248, .3)",
              shadowOffsetX: -2,
              shadowOffsetY: 2,
              shadowBlur: 10,
            },
          },
          // {
          //   data: data2,
          //   type: "effectScatter",
          //   coordinateSystem: "geo",
          //   symbolSize: function (val) {
          //     return 4;
          //     // return val[2] / 50;
          //   },
          //   legendHoverLink: true,
          //   showEffectOn: "render",
          //   rippleEffect: {
          //     // period: 4,
          //     scale: 6,
          //     color: "rgba(255,255,255, 1)",
          //     brushType: "fill",
          //   },
          //   tooltip: {
          //     show: true,
          //     formatter: function (params) {
          //       if (params.data) {
          //         return params.name + "：" + params.data["value"][2];
          //       } else {
          //         return params.name;
          //       }
          //     },
          //     backgroundColor: "rgba(0,0,0,.6)",
          //     borderColor: "rgba(147, 235, 248, .8)",
          //     textStyle: {
          //       color: "#FFF",
          //     },
          //   },
          //   label: {
          //     formatter: (param) => {
          //       return param.name.slice(0, 2);
          //     },

          //     fontSize: 11,
          //     offset: [0, 2],
          //     position: "bottom",
          //     textBorderColor: "#fff",
          //     textShadowColor: "#000",
          //     textShadowBlur: 10,
          //     textBorderWidth: 0,
          //     color: "#FFF",
          //     show: true,
          //   },
          //   // colorBy: "data",
          //   itemStyle: {
          //     color: "rgba(255,255,255,1)",
          //     borderColor: "rgba(255,255,255,2)",
          //     borderWidth: 4,
          //     shadowColor: "#000",
          //     shadowBlur: 10,
          //   },
          // },
          {
            name: '气泡Top5',
            type: 'effectScatter',
            data: data2,
            symbol: 'pin', // 气泡
            coordinateSystem: 'geo',
            symbolSize: 40,
            tooltip: {
              show: true,
              formatter: function (params) {
                if (params.data) {
                  let value = params.data.value[2] ? params.data.value[2] : 0;
                  return params.name + "：" + value;
                } else {
                  return params.name;
                }
              },
              backgroundColor: "rgba(0,0,0,.6)",
              borderColor: "rgba(147, 235, 248, .8)",
              textStyle: {
                color: "#FFF",
              },
            },
            label: {
              normal: {
                show: true,
                textStyle: {
                  color: '#fff',
                  fontSize: 12
                },
                formatter: params => {
                  if (params.value[2]) {
                    return params.value[2];
                  }
                  return 0;
                }
              },
              emphasis: {
                show: false
              }
            },
            itemStyle: {
              normal: {
                color: '#fc5f81', // 地图点的颜色
                shadowBlur: 10,
                shadowColor: 'rgb(58,115,192)'
              }
            },
            showEffectOn: 'hover',
            rippleEffect: {
              brushType: 'stroke'
            },
            zlevel: 6
          }
        ],
         //动画效果
        animationDuration: 1000,
        animationEasing: 'linear',
        animationDurationUpdate: 1000
      };
      this.options = option;
    },
    message(text) {
      this.$Message({
        text: text,
        type: "warning",
      });
    },
    mapclick() {
      if (this.echartBindClick) return;
      //单击切换到级地图，当mapCode有值,说明可以切换到下级地图
      this.$refs.CenterMap.chart.on("click", (params) => {
        if (params.componentType === 'series' && params.seriesType === 'map') {
          // 确保点击的是地图系列
          // 点击北京
          if(params.name == '北京市'){
            // this.map_flag = false
            // return
          }
          if (params.data == null) {
            this.message("暂无下级区域地图! 请先后台配置地图!");
            return;
          } else {
              this.current = params.name;
              this.$store.commit('setAdcode', params.data.adcode);
              // 先将点击的地图数据入栈
              this.adcodes.push({ adcode: params.data.adcode, name: params.name });
              // 渲染地图
              this.getData(params.data.adcode);
          }
        }
      });
      this.echartBindClick = true;
    },
  },
};
</script>
<style lang="scss" scoped>
.centermap {
  margin-bottom: 30px;

  .maptitle {
    height: 60px;
    display: flex;
    justify-content: center;
    padding-top: 10px;
    box-sizing: border-box;

    .titletext {
      font-size: 28px;
      font-weight: 900;
      letter-spacing: 6px;
      background: linear-gradient(
        92deg,
        #0072ff 0%,
        #00eaff 48.8525390625%,
        #01aaff 100%
      );
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      margin: 0 10px;
    }

    .zuo,
    .you {
      background-size: 100% 100%;
      width: 29px;
      height: 20px;
      margin-top: 8px;
    }

    .zuo {
      background: url("../../assets/img/xiezuo.png") no-repeat;
    }

    .you {
      background: url("../../assets/img/xieyou.png") no-repeat;
    }
  }

  .mapwrap {
    height: 820px;
    width: 100%;
    // padding: 0 0 10px 0;
    box-sizing: border-box;
    position: relative;

    .quanguo {
      position: absolute;
      right: 20px;
      top: -70px;
      width: 80px;
      height: 28px;
      border: 1px solid #00eded;
      border-radius: 10px;
      color: #00f7f6;
      text-align: center;
      line-height: 26px;
      letter-spacing: 6px;
      cursor: pointer;
      box-shadow: 0 2px 4px rgba(0, 237, 237, 0.5),
        0 0 6px rgba(0, 237, 237, 0.4);
    }

    .current {
      position: absolute;
      right: 20px;
      top: -30px;
      width: 80px;
      height: 28px;
      border: 1px solid #00eded;
      border-radius: 10px;
      color: #00f7f6;
      text-align: center;
      line-height: 26px;
      letter-spacing: 6px;
      cursor: pointer;
      box-shadow: 0 2px 4px rgba(0, 237, 237, 0.5),
        0 0 6px rgba(0, 237, 237, 0.4);
    }
  }
}
</style>
